package com.xiaofei.producerconsumer;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

public class Producer implements Runnable{
	private volatile boolean isRunning=true;
	private BlockingQueue<Data>blockingQueue;
	private static final int SLEEP_TIME = 1000;
	public Producer(BlockingQueue<Data>blockingQueue){
		this.blockingQueue = blockingQueue;
	}
	
	@Override
	public void run() {
		Random r = new Random();
		System.out.println("Start producer "+Thread.currentThread().getName());
		try {
			while (isRunning) {
				int size = blockingQueue.size();
				Thread.sleep(r.nextInt(SLEEP_TIME));
				Data data = new Data(String.valueOf(r.nextInt(SLEEP_TIME)));
				System.out.println(data+" is put into queue. Current queue size:"+size);
				if(!blockingQueue.offer(data, 2, TimeUnit.SECONDS)){
					System.err.println("Failed to put "+data+" into queue");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void stop(){
		this.isRunning = false;
	}
}
